package cu.tedu.egweibo1.controller;

import cu.tedu.egweibo1.mapper.UserMapper;
import cu.tedu.egweibo1.pojo.dto.UserLoginDTO;
import cu.tedu.egweibo1.pojo.dto.UserRegDTO;
import cu.tedu.egweibo1.pojo.entity.User;
import cu.tedu.egweibo1.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/v1/users/")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("reg")
    public int reg(@RequestBody UserRegDTO userRegDTO) {
        UserVO userVO = userMapper.selectUser(userRegDTO.getUsername());
        if (userVO != null) {
            return 2;
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDTO, user);
        userMapper.insertUser(user);
        return 1;
    }


    @PostMapping("login")
    public int login(@RequestBody UserLoginDTO userLoginDTO, HttpSession session) {
        UserVO userVO = userMapper.selectUser(userLoginDTO.getUsername());
        if (userVO == null) {
            return 3;
        }
        if (userLoginDTO.getPassword().equals(userVO.getPassword())) {

            session.setAttribute("user", userVO);
            return 1;

        }
        return 2;
    }

    @GetMapping("currentUser")
    public UserVO currentUser(HttpSession session){
        return (UserVO) session.getAttribute("user");
    }
}
